package com.sweet.controller;


import com.sweet.Result;
import com.sweet.dto.CommonDto;
import com.sweet.lb.LoadBalancerImpl;
import com.sweet.utils.HeadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;


@RestController
public class OrderController {

    // private static final String PRE_PROVIDE_URL = "http://127.0.0.1:8001"; // 单机访问
    private static final String PRE_PROVIDE_URL = "http://SWEET-PROVIDER-PAYMENT"; // 集群使用app名称

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerImpl loadBalancer;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/orders")
    public Result getOrder(CommonDto dto) {
        if (dto.getCurPage() == null) {
            dto.setCurPage(1);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(10);
        }
        // 请求头
        HttpEntity<String> entity = HeadUtils.templateHttpEntity();
        // 请求参数
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.set("curPage", String.valueOf(dto.getCurPage()));
        map.set("pageSize", String.valueOf(dto.getPageSize()));
        // url
        String completeUrl = HeadUtils.getCompleteUrl(PRE_PROVIDE_URL + "/orders", map);

        ResponseEntity<Result> result = restTemplate.exchange(
                completeUrl, HttpMethod.GET, entity, Result.class);
        return Result.ok(result.getBody().getResult());
    }

    @GetMapping("/consumer/lb")
    public String getPort() {
        List<ServiceInstance> instances = discoveryClient.getInstances("SWEET-PROVIDER-PAYMENT");
        ServiceInstance instance = loadBalancer.getInstanceFromInstances(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin()
    {
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin/", String.class);
        return result;
    }
}
